<?php

namespace App\Store\Controllers\Order;

use App\Common\Services\CommonExcelExport;
use App\Store\Models\OldMaterial\Stock;
use App\Store\Models\Order\OrderSalesGoods;
use App\Store\Models\Order\OrderSalesRecoveryGoods;
use App\Store\Services\Goods\Goods;
use App\Store\Services\Member\CommonMember;
use App\Store\Services\Message\WxaccountMessage;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Store\Models\Member\MemberBalanceChangelog;
use App\Store\Models\Order\OrderRecovery;
use App\Common\Services\Store\Common as StoreCommon;
use App\Store\Models\Member\Member;
use App\Store\Models\Basic\GoodsCategory;
use App\Store\Models\Basic\PaytypeList;
use App\Store\Models\Goods\GoodsGlodprice;
use App\Store\Models\Goods\GoodsStockList;
use App\Store\Models\Member\MemberPointsChangelog;
use App\Store\Models\Order\OrderCommissionLog;
use App\Store\Models\Order\OrderRecoveryGoods;
use App\Store\Services\Financial;
use Illuminate\Support\Facades\DB;
use App\Store\Validate\Order\OrderRecovery as ValidateOrderOrderRecovery;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Facades\Excel;

use App\Store\Services\Order\OrderRecovery as ServicesOrderOrderRecovery;

use App\Store\Validate\Order\OrderSales as ValidateOrderOrderSales;
use function Symfony\Component\Translation\t;

/**
 * 纯回收开单
 */
class OrderRecoveryController extends Controller
{
    /**
     * 开单
     */
    public function dopostorder(Request $request)
    {
        $req_data = $request->only([
            'mobile', 'real_name', 'mem_card_no', 'lunar_bdate', 'solar_bdate', 'points_current', 'sub_goods', 'money', 'shopping_account_id1', 'shopping_account_id2', 'classesset_id', 'pay_type_id', 'order_at', 'issendpoints', 'remark', 'mixed_payment','pay_money'
        ]);
        $Validate = new ValidateOrderOrderRecovery();
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }

        if (!empty($req_data['mixed_payment'])) {
            foreach ($req_data['mixed_payment'] as $money) {
                if ($req_data['pay_money'] > 0 && $money < 0) {
                    return response()->json(['code' => '001', 'msg' => '输入的金额有误']);
                }
                if ($req_data['pay_money'] < 0 && $money > 0) {
                    return response()->json(['code' => '001', 'msg' => '输入的金额有误']);
                }
            }
        }


        $sub_goods = is_array($req_data['sub_goods']) ? $req_data['sub_goods'] : (is_array(json_decode($req_data['sub_goods'], true)) ? json_decode($req_data['sub_goods'], true) : []);

        if (count($sub_goods) <= 0) {
            return response()->json(['code' => '001', 'msg' => '旧料信息不能为空']);
        }
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $current_store_id = 0;
        $store_ids = $accountinfo['store_ids'];
        if ($store_ids) { //权限控制
            if (is_array($store_ids) || $store_ids == '') { //获取当前权限下的门店
                return response()->json(['code' => '001', 'msg' => '请使用店长或店员账号']);
            }
            if (is_numeric($store_ids) && intval($store_ids) > 0) { //获取当前门店下的列表
                $current_store_id = intval($store_ids);
            }
        }
        $sub_arr = [];

        $ValidateSub = new ValidateOrderOrderRecovery('subgoods');
        foreach ($sub_goods as $goods) {

            if (!$ValidateSub->check($goods)) {
                return response()->json(['code' => '001', 'msg' => $ValidateSub->getError()]);
            }
            if ($goods['recovery_type'] == 1) {
                $ValidateSub1 = new ValidateOrderOrderRecovery('subgoods1');
                if (!$ValidateSub1->check($goods)) {
                    return response()->json(['code' => '001', 'msg' => $ValidateSub1->getError()]);
                }
            }
            if ($goods['change_type'] == 2) {
                $ValidateSub2 = new ValidateOrderOrderRecovery('subgoods2');
                if (!$ValidateSub2->check($goods)) {
                    return response()->json(['code' => '001', 'msg' => $ValidateSub2->getError()]);
                }

                if (!isset($goods['goods_sn_code']) || $goods['goods_sn_code'] == '') {
                    return response()->json(['code' => '001', 'msg' => '旧料上柜条码不能为空']);
                } else {
                    //查询商品库存是否存在此商品
                    $isexist = GoodsStockList::with(['goods_category'])->where(['cp_id' => $cp_id, 'goods_sn_code' => $goods['goods_sn_code'], 'store_id' => $current_store_id, 'is_del' => 1])->first();
                    if (!$isexist) {
                        return response()->json(['code' => '001', 'msg' => '不存在此商品无法上柜']);
                    }
                }
            }

            $sales_goods_id = $goods['sales_goods_id'] ?? 0;
            $saleGoodsInfo = [];
            if ($sales_goods_id > 0) {
                $saleGoodsInfo = OrderSalesGoods::query()->where('id', $sales_goods_id)->first();
                $saleGoodsInfo = empty($saleGoodsInfo) ? [] : $saleGoodsInfo->toArray();
                $saleGoodsInfo['goodsinfo'] = json_decode($saleGoodsInfo['goodsinfo'], true);
                $saleGoodsInfo['goods_style_id'] = $saleGoodsInfo['goodsinfo']['goods_style_id'] ?? 0;
                $saleGoodsInfo['is_code_more'] = $saleGoodsInfo['goodsinfo']['is_code_more'] ?? 0;
            }


            if ($goods['change_type'] == 2) {
                $salesRecoveryGoods = OrderSalesRecoveryGoods::query()
                    ->where(['cp_id' => $cp_id, 'is_del' => 1, 'goods_sn_code' => $goods['goods_sn_code'], 'change_type' => 2])
                    ->where('audit_status', '<>', 3)
                    ->selectRaw('sum(count) as total')
                    ->first();
                $salesRecoveryGoods = empty($salesRecoveryGoods) ? [] : $salesRecoveryGoods->toArray();

                $recoverygoods = OrderRecoveryGoods::query()
                    ->where(['cp_id' => $cp_id, 'is_del' => 1, 'goods_sn_code' => $goods['goods_sn_code'], 'change_type' => 2])
                    ->where('audit_status', '<>', 3)
                    ->selectRaw('sum(count) as total')
                    ->first();
                $recoverygoods = empty($recoverygoods) ? [] : $recoverygoods->toArray();

                $count = $goods['count'] + ($recoverygoods['total'] ?? 0) + ($salesRecoveryGoods['total'] ?? 0);

                $orderSales = OrderSalesGoods::query()
                    ->where(['cp_id' => $cp_id, 'is_del' => 1, 'goods_sn_code' => $goods['goods_sn_code'], 'red_status' => 1])
                    ->where('audit_status', '<>', 3)
                    ->selectRaw('sum(count) as total')
                    ->first();

                if (empty($orderSales)) {
                    return response()->json(['code' => '001', 'msg' => '本厂不存在此商品无法上柜']);
                }

                if ((int)$count > (int)$orderSales['total']) {
                    return response()->json(['code' => '001', 'msg' => '上柜的商品数量不能大于本厂的商品数量']);
                }

                if ($sales_goods_id <= 0) {
                    return response()->json(['code' => '001', 'msg' => '上柜的商品不存在']);
                }

            }

            $goods_categoryinfo = GoodsCategory::where('id', $goods['goods_category_id'])->first();

            $lastprice = GoodsGlodprice::where(['cp_id' => $cp_id, 'store_id' => $current_store_id, 'goods_category_id' => $goods['goods_category_id'], 'is_del' => 1])
                ->where('date_str', '<=', date('Y-m-d'))->orderBy('date_str', 'desc')->first();
            $item = [
                'cp_id' => $cp_id,
                'store_id' => $current_store_id,
                'shopping_account_id1' => isset($req_data['shopping_account_id1']) ? (int)$req_data['shopping_account_id1'] : 0,
                'shopping_account_id2' => isset($req_data['shopping_account_id2']) ? (int)$req_data['shopping_account_id2'] : 0,
                'money' => abs($goods['money']),
                'change_type' => $goods['change_type'],
                'recovery_type' => $goods['recovery_type'],
                'goods_category_id' => $goods['goods_category_id'],
                'goods_catefory_name' => GoodsCategory::where(['cp_id' => $cp_id, 'id' => $goods['goods_category_id']])->value('category_name'),
                'goods_sn_code' => isset($goods['goods_sn_code']) ? $goods['goods_sn_code'] : '',
                'count' => $goods['count'],
                'weight' => isset($goods['weight']) ? (double)$goods['weight'] : 0,
                'price' => isset($goods['price']) ? (int)$goods['price'] : 0,
                'd_price' => isset($goods['d_price']) ? (int)$goods['d_price'] : 0,
                'discount' => isset($goods['discount']) ? (int)$goods['discount'] : 0,
                'dold_price' => isset($goods['dold_price']) ? (int)$goods['dold_price'] : 0,
                'dold_fee' => isset($goods['dold_fee']) ? (int)$goods['dold_fee'] : 0,
                'loss_weight' => isset($goods['loss_weight']) ? (double)$goods['loss_weight'] : 0,
                'remark' => isset($goods['remark']) ? $goods['remark'] : '',
                'create_at' => time(),
                'update_at' => time(),
                'sales_price' => $lastprice ? $lastprice->sales_price : 0,
                'old_recovery_price' => $lastprice ? $lastprice->back_company_price : 0,
                'cost_fee' => ($goods['change_type'] == 2 && isset($isexist)) ? ($isexist['goods_category']['is_gram'] == 1 ? (($isexist['costglod_price'] + $isexist['costglod_price']) * $isexist['netglod_weight']) : $isexist['piececost_fee']) : 0,
                'is_sujin' => $goods_categoryinfo['is_sujin'],
                'sales_goods_id' => $sales_goods_id ?? 0,
                'is_code_more' => $saleGoodsInfo['is_code_more'] ?? 0,
                'goods_style_id' => $saleGoodsInfo['goods_style_id'] ?? 0,
                'total_money' => $sales_goods_id > 0 ? intval(bcmul(bcdiv($saleGoodsInfo['real_total_money'], $saleGoodsInfo['count'], 2), $goods['count'])) : 0,
                'sales_goods_performance' => $saleGoodsInfo['performance'] ?? 0
            ];
            $item['valuations'] = ($item['old_recovery_price'] * $item['weight']);
            $sub_arr[] = $item;
        }


        $orderdata = [
            'total_money' => abs($req_data['money']),
            'shopping_account_id1' => isset($req_data['shopping_account_id1']) ? (int)$req_data['shopping_account_id1'] : 0,
            'shopping_account_id2' => isset($req_data['shopping_account_id2']) ? (int)$req_data['shopping_account_id2'] : 0,
            'classesset_id' => isset($req_data['classesset_id']) ? intval($req_data['classesset_id']) : 0,
            'pay_type_id' => $req_data['pay_type_id'],
            'mixed_payment' => (empty($req_data['mixed_payment']) || $req_data['mixed_payment'] == '{}') ? '' : json_encode($req_data['mixed_payment']),
            'order_at' => isset($req_data['order_at']) ? strtotime($req_data['order_at']) : time(),
            'issendpoints' => isset($req_data['issendpoints']) ? intval($req_data['issendpoints']) : 1,
            'remark' => isset($req_data['remark']) ? $req_data['remark'] : ''
        ];
        // $orderdata['order_at'] = strtotime($orderdata['order_at']);
        if (isset($req_data['mobile']) && !empty($req_data['mobile'])) {
            $meminfo = Member::where(['cp_id' => $cp_id, 'mobile' => $req_data['mobile'], 'is_del' => 1])->first();

            if (!$meminfo) {
                $memdata = [
                    'cp_id' => $cp_id,
                    'store_id' => $current_store_id,
                    'mobile' => $req_data['mobile'],
                    'real_name' => isset($req_data['real_name']) ? $req_data['real_name'] : '',
                    'mem_card_no' => isset($req_data['mem_card_no']) ? $req_data['mem_card_no'] : '',
                    'lunar_bdate' => isset($req_data['lunar_bdate']) ? $req_data['lunar_bdate'] : '',
                    'solar_bdate' => isset($req_data['solar_bdate']) ? $req_data['solar_bdate'] : '',
                    'points_current' => isset($req_data['points_current']) ? intval($req_data['points_current']) : 0,
                    'create_at' => time(),
                    'update_at' => time(),
                    'create_account_id' => $accountinfo['id'],
                    'update_account_id' => $accountinfo['id'],
                    'create_account_real_name' => $accountinfo['real_name'],
                    'update_account_real_name' => $accountinfo['real_name'],
                ];
                $ins_mem_id = Member::create($memdata);
                CommonMember::setMemInitPoints($request, $ins_mem_id);
            }
            $meminfo = Member::where(['cp_id' => $cp_id, 'mobile' => $req_data['mobile'], 'is_del' => 1])->first();
        } else {
            $meminfo = json_decode(json_encode(['id' => 0, 'pre_money' => 0, 'pointstobalance' => 0]));
        }


        $orderdata['mem_id'] = $meminfo->id;

        $orderdata['cp_id'] = $cp_id;
        $orderdata['store_id'] = $current_store_id;
        $orderdata['order_sn'] = StoreCommon::createOrderSn();
        $orderdata['pay_type_name'] = $req_data['pay_type_id'] == -1 ? '混合支付' : PaytypeList::where(['id' => $req_data['pay_type_id']])->value('paytype_name');

        $orderdata['create_account_id'] = $accountinfo['id'];
        $orderdata['update_account_id'] = $accountinfo['id'];
        $orderdata['create_account_real_name'] = $accountinfo['real_name'];
        $orderdata['update_account_real_name'] = $accountinfo['real_name'];
        $orderdata['create_at'] = time();
        $orderdata['update_at'] = time();

        $sub_arr = ServicesOrderOrderRecovery::computePerformanceAndCommission($sub_arr);


        DB::beginTransaction();
        try {

            $pid = OrderRecovery::create($orderdata)->id;
            $ordercommissionlog = [];
            foreach ($sub_arr as &$sub) {
                $sub['pid'] = $pid;
                $sub['mem_id'] = $meminfo->id;
                $sub['order_at'] = $orderdata['order_at'];
                $sub['classesset_id'] = $orderdata['classesset_id'];

                // 此处需要取卖的出去的订单商品最后一条数据的总成本
                $goodsinfo = [];
                $sub['total_netglod_weight'] = 0;
                if (!empty($sub['goods_sn_code'])) {
                    $salesGoods = OrderSalesGoods::query()
                        ->where('cp_id', $cp_id)
                        ->where('is_del', 1)
                        ->where('goods_sn_code', $sub['goods_sn_code'])
                        ->orderBy('id', 'desc')
                        ->first();

                    $salesGoods = empty($salesGoods) ? [] : $salesGoods->toArray();
                    $goodsinfo = empty($salesGoods) ? [] : (array)(json_decode($salesGoods['goodsinfo']));
                    if (!empty($goodsinfo)) {
                        if ($goodsinfo['is_code_more'] == 2) {
                            $sub['total_netglod_weight'] = $sub['weight'];
                        } else {
                            $sub['total_netglod_weight'] = $goodsinfo['netglod_weight'] * $sub['count'];
                        }
                    }


                }


                //  list($deduct_total_cost_fee, $remaining_cost_fee) = (new Goods())->deductTotalCost($salesGoods, ['total_netglod_weight' => ($sub['weight'] - $sub['loss_weight'])]);
                list($deduct_total_cost_fee, $remaining_cost_fee) = (new Goods())->deductTotalCost($goodsinfo, ['total_netglod_weight' => $sub['total_netglod_weight']]);
                $sub['total_cost_fee'] = $deduct_total_cost_fee;


                $sub_id = OrderRecoveryGoods::create($sub)->id;
                $ordercommissionlog[] = [
                    'cp_id' => $cp_id,
                    'store_id' => $sub['store_id'],
                    'pid' => $pid,
                    'sub_id' => $sub_id,
                    'type' => 6,
                    'commission1' => $sub['commission1'],
                    'commission2' => 0,
                    'order_at' => $orderdata['order_at'],
                    'create_at' => $orderdata['create_at'],
                    'classesset_id' => $orderdata['classesset_id'],
                    'goods_style_id' => 0,
                    'order_sn' => $orderdata['order_sn'],
                    'shopping_account_id1' => $orderdata['shopping_account_id1'],
                    'shopping_account_id2' => $orderdata['shopping_account_id2'],
                ];
            }

            OrderCommissionLog::insert($ordercommissionlog);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();

            info('纯回收开单失败' . $e->getFile() . $e->getLine() . $e->getMessage());
            return response()->json(['code' => '001', 'msg' => '开单失败']);
        }
        $printdata = $request->is_print == 1 ? ServicesOrderOrderRecovery::getOrderPrintData($pid, $request) : [];
        $info = OrderRecovery::query()
            ->where('id', $pid)
            ->first();
        if (!empty($info)) {
            $recoverygoodslist = OrderRecoveryGoods::where(['pid' => $pid, 'is_del' => 1])->get()->toArray();

            $info = $info->toArray();
            $info['total_money'] = -$info['total_money'];
            foreach ($recoverygoodslist as &$item) {
                $item['money'] = -$item['money'];
            }

            $info['count'] = array_sum(array_column($recoverygoodslist, 'count'));
            $info['money'] = array_sum(array_column($recoverygoodslist, 'money'));

            $info['mem_id'] > 0 && WxaccountMessage::sendwx($cp_id, $info['mem_id'], 'recovery_order', $info);
            WxaccountMessage::sendwxinner($cp_id, $info['store_id'], 'recovery_order', $info);
        }

        return response()->json(['code' => '000', 'msg' => '开单成功', 'data' => $printdata]);
    }

    /**
     * 挂单
     */
    public function dopostordermaker(Request $request)
    {

        $req_data = $request->only([
            'mobile', 'real_name', 'mem_card_no', 'lunar_bdate', 'solar_bdate', 'points_current', 'sub_goods', 'money', 'shopping_account_id1', 'shopping_account_id2', 'classesset_id', 'pay_type_id', 'order_at', 'issendpoints', 'remark', 'mixed_payment',
        ]);
        $Validate = new ValidateOrderOrderRecovery();
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }

        $sub_goods = is_array($req_data['sub_goods']) ? $req_data['sub_goods'] : (is_array(json_decode($req_data['sub_goods'], true)) ? json_decode($req_data['sub_goods'], true) : []);

        if (count($sub_goods) <= 0) {
            return response()->json(['code' => '001', 'msg' => '旧料信息不能为空']);
        }
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $current_store_id = 0;
        $store_ids = $accountinfo['store_ids'];
        if ($store_ids) { //权限控制
            if (is_array($store_ids) || $store_ids == '') { //获取当前权限下的门店

                return response()->json(['code' => '001', 'msg' => '请使用店长或店员账号']);
            }
            if (is_numeric($store_ids) && intval($store_ids) > 0) { //获取当前门店下的列表
                $current_store_id = intval($store_ids);
            }
        }
        $sub_arr = [];

        $ValidateSub = new ValidateOrderOrderRecovery('subgoods');
        foreach ($sub_goods as $goods) {

            if (!$ValidateSub->check($goods)) {
                return response()->json(['code' => '001', 'msg' => $ValidateSub->getError()]);
            }
            if ($goods['recovery_type'] == 1) {
                $ValidateSub1 = new ValidateOrderOrderRecovery('subgoods1');
                if (!$ValidateSub1->check($goods)) {
                    return response()->json(['code' => '001', 'msg' => $ValidateSub1->getError()]);
                }
            }
            if ($goods['recovery_type'] == 2) {
                $ValidateSub2 = new ValidateOrderOrderRecovery('subgoods2');
                if (!$ValidateSub2->check($goods)) {
                    return response()->json(['code' => '001', 'msg' => $ValidateSub2->getError()]);
                }
            }

            if ($goods['change_type'] == 2 && (!isset($goods['goods_sn_code']) || $goods['goods_sn_code'] == '')) {

                return response()->json(['code' => '001', 'msg' => '旧料上柜条码不能为空']);
            }

            // 此处需要取卖的出去的订单商品最后一条数据的总成本
            $goodsinfo = [];
            $goods['total_netglod_weight'] = 0;
            if (!empty($goods['goods_sn_code'])) {
                $salesGoods = OrderSalesGoods::query()
                    ->where('cp_id', $cp_id)
                    ->where('is_del', 1)
                    ->where('goods_sn_code', $goods['goods_sn_code'])
                    ->orderBy('id', 'desc')
                    ->first();


                $salesGoods = empty($salesGoods) ? [] : $salesGoods->toArray();
                $goodsinfo = empty($salesGoods) ? [] : (array)(json_decode($salesGoods['goodsinfo']));
                if (!empty($goodsinfo)) {
                    if ($goodsinfo['is_code_more'] == 2) {
                        $goods['total_netglod_weight'] = $goods['weight'] * $goods['count'];
                    } else {
                        $goods['total_netglod_weight'] = $goodsinfo['netglod_weight'] * $goods['count'];
                    }
                }

            }

            list($deduct_total_cost_fee, $remaining_cost_fee) = (new Goods())->deductTotalCost($goodsinfo, ['total_netglod_weight' => $goods['total_netglod_weight']]);
            $item = [
                'cp_id' => $cp_id,
                'store_id' => $current_store_id,
                'shopping_account_id1' => $req_data['shopping_account_id1'],
                'shopping_account_id2' => $req_data['shopping_account_id2'],
                'money' => abs($goods['money']),
                'change_type' => $goods['change_type'],
                'recovery_type' => $goods['recovery_type'],
                'goods_category_id' => $goods['goods_category_id'],
                'goods_catefory' => GoodsCategory::where(['cp_id' => $cp_id, 'id' => $goods['goods_category_id']])->value('category_name'),
                'goods_sn_code' => isset($goods['goods_sn_code']) ? $goods['goods_sn_code'] : '',
                'count' => $goods['count'],
                'weight' => isset($goods['weight']) ? (double)$goods['weight'] : 0,
                'price' => isset($goods['price']) ? (int)$goods['price'] : 0,
                'd_price' => isset($goods['d_price']) ? (int)$goods['d_price'] : 0,
                'discount' => isset($goods['discount']) ? (int)$goods['discount'] : 0,
                'dold_price' => isset($goods['dold_price']) ? (int)$goods['dold_price'] : 0,
                'dold_fee' => isset($goods['dold_fee']) ? (int)$goods['dold_fee'] : 0,
                'loss_weight' => isset($goods['loss_weight']) ? (double)$goods['loss_weight'] : 0,
                'remark' => isset($goods['remark']) ? $goods['remark'] : '',
                'create_at' => time(),
                'update_at' => time(),
                'total_cost_fee' => $deduct_total_cost_fee
            ];
            $sub_arr[] = $item;
        }

        $orderdata = [
            'money' => abs($req_data['money']),
            'shopping_account_id1' => $req_data['shopping_account_id1'],
            'shopping_account_id2' => $req_data['shopping_account_id2'],
            'classesset_id' => $req_data['classesset_id'],
            'pay_type_id' => $req_data['pay_type_id'],
            'mixed_payment' => (empty($req_data['mixed_payment']) || $req_data['mixed_payment'] == '{}') ? '' : json_encode($req_data['mixed_payment']),
            'order_at' => $req_data['order_at'],
            'issendpoints' => $req_data['issendpoints'],
            'remark' => isset($req_data['remark']) ? $req_data['remark'] : ''
        ];
        $orderdata['order_at'] = strtotime($orderdata['order_at']);
        if (isset($req_data['mobile']) && !empty($req_data['mobile'])) {
            $meminfo = Member::where(['cp_id' => $cp_id, 'mobile' => $req_data['mobile'], 'is_del' => 1])->first();

            if (!$meminfo) {
                $memdata = [
                    'cp_id' => $cp_id,
                    'store_id' => $current_store_id,
                    'mobile' => $req_data['mobile'],
                    'real_name' => isset($req_data['real_name']) ? $req_data['real_name'] : '',
                    'mem_card_no' => isset($req_data['mem_card_no']) ? $req_data['mem_card_no'] : '',
                    'lunar_bdate' => isset($req_data['lunar_bdate']) ? $req_data['lunar_bdate'] : '',
                    'solar_bdate' => isset($req_data['solar_bdate']) ? $req_data['solar_bdate'] : '',
                    'points_current' => isset($req_data['points_current']) ? intval($req_data['points_current']) : 0,
                    'create_at' => time(),
                    'update_at' => time(),
                    'create_account_id' => $accountinfo['id'],
                    'update_account_id' => $accountinfo['id'],
                    'create_account_real_name' => $accountinfo['real_name'],
                    'update_account_real_name' => $accountinfo['real_name'],
                ];
                $ins_mem_id = Member::create($memdata)->id;
                CommonMember::setMemInitPoints($request, $ins_mem_id);
            }

        }
        $meminfo = Member::where(['cp_id' => $cp_id, 'mobile' => $req_data['mobile'], 'is_del' => 1])->first();
        $orderdata['mem_id'] = $meminfo->id;

        $orderdata['cp_id'] = $cp_id;
        $orderdata['store_id'] = $current_store_id;
        $orderdata['order_sn'] = date('YmdHis') . $cp_id . $current_store_id . random_int(1000, 9999);
        $orderdata['pay_type_name'] = $req_data['pay_type_id'] == -1 ? '混合支付' : PaytypeList::where(['id' => $req_data['pay_type_id']])->value('paytype_name');

        $orderdata['create_account_id'] = $accountinfo['id'];
        $orderdata['update_account_id'] = $accountinfo['id'];
        $orderdata['create_account_real_name'] = $accountinfo['real_name'];
        $orderdata['update_account_real_name'] = $accountinfo['real_name'];
        $orderdata['create_at'] = time();
        $orderdata['update_at'] = time();
        // $orderdata['is_maker']=2;

        DB::beginTransaction();
        try {
            $pid = OrderRecovery::create($orderdata)->id;
            foreach ($sub_arr as &$sub) {
                $sub['pid'] = $pid;
                $sub['mem_id'] = $meminfo->id;
            }
            OrderRecoveryGoods::insert($sub_arr);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '挂单失败' . $e->getMessage()]);
        }

        return response()->json(['code' => '000', 'msg' => '挂单成功']);
    }

    /**
     * 挂单支付
     */
    public function doordermakerpay(Request $request)
    {
        $id = $request->id ?? 0;
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $info = OrderRecovery::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        if ($info->audit_status != 1) {
            return response()->json(['code' => '001', 'msg' => '该订单已审核']);
        }
        // if($info->is_maker!=2){
        //     return response()->json(['code' => '001', 'msg' => '该订单不是挂单状态']);
        // }
        OrderRecovery::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['is_maker' => 1, 'update_at' => time()]);
        return response()->json(['code' => '000', 'msg' => '订单支付成功']);
    }

    /**
     * 订单列表
     */

    public function getorderlist(Request $request)
    {
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        if ($accountinfo['type'] == 11) {
            $training = StoreCommon::gettraining($request);
            if ($training['training_min'] == 0 && $training['training_max'] == 0) {
                return response()->json(['code' => '001', 'msg' => '培训账号，请先设置公司培训上下限']);
            }
            $request->training_min = $training['training_min'];
            $request->training_max = $training['training_max'];
        }
        $list = OrderRecovery::getList($request);
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $list]);
    }

    /**
     * 订单详情
     */
    public function getinfo(Request $request)
    {
        $id = $request->id ?? 0;
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $info = OrderRecovery::with(['memberinfo', 'shoppingaccountinfo1', 'shoppingaccountinfo2', 'storeinfo', 'goodslist'])
            ->where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->first();
        if (empty($info)) {
            return response()->json(['code' => '001', 'msg' => '数据不存在']);
        }

        $info = $info->toArray();
        $info['total_money'] = -$info['total_money'];

        foreach ($info['goodslist'] as &$item) {
            $item['money'] = -$item['money'];
        }


        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['info' => $info]]);

    }

    public function getinfobyordersn(Request $request)
    {
        $order_sn = $request->order_sn ?? '';
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $info = OrderRecovery::with(['memberinfo', 'shoppingaccountinfo1', 'shoppingaccountinfo2', 'storeinfo', 'goodslist'])->where(['order_sn' => $order_sn, 'cp_id' => $cp_id, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        $info = $info->toArray();
        $info['total_money'] = -$info['total_money'];
        $info['recoverygoodslist'] = $info['goodslist'];
        unset($info['goodslist']);


        foreach ($info['recoverygoodslist'] as &$item) {
            $item['money'] = -$item['money'];
        }


        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['info' => $info]]);
    }

    /**
     * 编辑
     */
    public function doorderedit(Request $request)
    {

        $req_data = $request->only([
            'id', 'sub_goods', 'money', 'shopping_account_id1', 'shopping_account_id2', 'classesset_id', 'pay_type_id', 'order_at', 'issendpoints', 'remark', 'mixed_payment',
        ]);
        $id = $request->id ?? 0;

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];

        $info = OrderRecovery::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        $Validate = new ValidateOrderOrderRecovery('edit');
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }

        $sub_goods = is_array($req_data['sub_goods']) ? $req_data['sub_goods'] : (is_array(json_decode($req_data['sub_goods'], true)) ? json_decode($req_data['sub_goods'], true) : []);

        if (count($sub_goods) <= 0) {
            return response()->json(['code' => '001', 'msg' => '旧料信息不能为空']);
        }

        $current_store_id = 0;
        $store_ids = $accountinfo['store_ids'];
        if ($store_ids) { //权限控制
            if (is_array($store_ids) || $store_ids == '') { //获取当前权限下的门店

                return response()->json(['code' => '001', 'msg' => '请使用店长或店员账号']);
            }
            if (is_numeric($store_ids) && intval($store_ids) > 0) { //获取当前门店下的列表
                $current_store_id = intval($store_ids);
            }
        }
        $sub_arr = [];

        $ValidateSub = new ValidateOrderOrderRecovery('subgoods');
        foreach ($sub_goods as $goods) {

            if (!$ValidateSub->check($goods)) {
                return response()->json(['code' => '001', 'msg' => $ValidateSub->getError()]);
            }
            if ($goods['recovery_type'] == 1) {
                $ValidateSub1 = new ValidateOrderOrderRecovery('subgoods1');
                if (!$ValidateSub1->check($goods)) {
                    return response()->json(['code' => '001', 'msg' => $ValidateSub1->getError()]);
                }
            }
            if ($goods['recovery_type'] == 2) {
                $ValidateSub2 = new ValidateOrderOrderRecovery('subgoods2');
                if (!$ValidateSub2->check($goods)) {
                    return response()->json(['code' => '001', 'msg' => $ValidateSub2->getError()]);
                }
            }

            if ($goods['change_type'] == 2 && (!isset($goods['goods_sn_code']) || $goods['goods_sn_code'] == '')) {

                return response()->json(['code' => '001', 'msg' => '旧料上柜条码不能为空']);
            }


            // 此处需要取卖的出去的订单商品最后一条数据的总成本
            $goodsinfo = [];
            if (!empty($goods['goods_sn_code'])) {
                $salesGoods = OrderSalesGoods::query()
                    ->where('cp_id', $cp_id)
                    ->where('is_del', 1)
                    ->where('order_sn', $goods['goods_sn_code'])
                    ->orderBy('id', 'desc')
                    ->first();

                $salesGoods = empty($salesGoods) ? [] : $salesGoods->toArray();
                $goodsinfo = empty($salesGoods) ? [] : (array)(json_decode($salesGoods['goodsinfo']));
                if (!empty($goodsinfo)) {
                    if ($goodsinfo['is_code_more'] == 2) {
                        $goods['total_netglod_weight'] = $goods['weight'] * $goods['count'];
                    } else {
                        $goods['total_netglod_weight'] = $goodsinfo['netglod_weight'] * $goods['count'];
                    }

                }

            }


            list($deduct_total_cost_fee, $remaining_cost_fee) = (new Goods())->deductTotalCost($goodsinfo, ['total_netglod_weight' => ($goods['total_netglod_weight'])]);

            $item = [
                'cp_id' => $cp_id,
                'store_id' => $current_store_id,
                'shopping_account_id1' => $req_data['shopping_account_id1'],
                'shopping_account_id2' => $req_data['shopping_account_id2'],
                'money' => abs($goods['money']),
                'change_type' => $goods['change_type'],
                'recovery_type' => $goods['recovery_type'],
                'goods_category_id' => $goods['goods_category_id'],
                'goods_catefory' => GoodsCategory::where(['cp_id' => $cp_id, 'id' => $goods['goods_category_id']])->value('category_name'),
                'goods_sn_code' => isset($goods['goods_sn_code']) ? $goods['goods_sn_code'] : '',
                'count' => $goods['count'],
                'weight' => isset($goods['weight']) ? $goods['weight'] : 0,
                'price' => isset($goods['price']) ? $goods['price'] : 0,
                'd_price' => isset($goods['d_price']) ? $goods['d_price'] : 0,
                'discount' => isset($goods['discount']) ? $goods['discount'] : 0,
                'dold_price' => isset($goods['dold_price']) ? $goods['dold_price'] : 0,
                'dold_fee' => isset($goods['dold_fee']) ? $goods['dold_fee'] : 0,
                'loss_weight' => isset($goods['loss_weight']) ? $goods['loss_weight'] : 0,
                'remark' => isset($goods['remark']) ? $goods['remark'] : '',
                'create_at' => time(),
                'update_at' => time(),
                'total_cost_fee' => $deduct_total_cost_fee
            ];
            $sub_arr[] = $item;
        }

        $orderdata = [
            'money' => abs($req_data['money']),
            'shopping_account_id1' => $req_data['shopping_account_id1'],
            'shopping_account_id2' => $req_data['shopping_account_id2'],
            'classesset_id' => $req_data['classesset_id'],
            'pay_type_id' => $req_data['pay_type_id'],
            'mixed_payment' => (empty($req_data['mixed_payment']) || $req_data['mixed_payment'] == '{}') ? '' : json_encode($req_data['mixed_payment']),
            'order_at' => $req_data['order_at'],
            'issendpoints' => $req_data['issendpoints'],
            'remark' => isset($req_data['remark']) ? $req_data['remark'] : ''
        ];
        $orderdata['order_at'] = strtotime($orderdata['order_at']);
        $meminfo = Member::where(['cp_id' => $cp_id, 'mobile' => $req_data['mobile'], 'is_del' => 1])->first();

        if (!empty($meminfo)) {
            $memdata = [
                'cp_id' => $cp_id,
                'store_id' => $current_store_id,
                'mobile' => $req_data['mobile'],
                'real_name' => isset($req_data['real_name']) ? $req_data['real_name'] : '',
                'mem_card_no' => isset($req_data['mem_card_no']) ? $req_data['mem_card_no'] : '',
                'lunar_bdate' => isset($req_data['lunar_bdate']) ? $req_data['lunar_bdate'] : '',
                'solar_bdate' => isset($req_data['solar_bdate']) ? $req_data['solar_bdate'] : '',
                'points_current' => isset($req_data['points_current']) ? intval($req_data['points_current']) : 0,
                'create_at' => time(),
                'update_at' => time(),
                'create_account_id' => $accountinfo['id'],
                'update_account_id' => $accountinfo['id'],
                'create_account_real_name' => $accountinfo['real_name'],
                'update_account_real_name' => $accountinfo['real_name'],
            ];
            Member::create($memdata);
        }
        $meminfo = Member::where(['cp_id' => $cp_id, 'mobile' => $req_data['mobile'], 'is_del' => 1])->first();
        $orderdata['mem_id'] = $meminfo->id;
        $orderdata['order_sn'] = StoreCommon::createOrderSn();
        $orderdata['pay_type_name'] = $req_data['pay_type_id'] == -1 ? '混合支付' : PaytypeList::where(['id' => $req_data['pay_type_id']])->value('paytype_name');

        $orderdata['update_account_id'] = $accountinfo['id'];
        $orderdata['update_account_real_name'] = $accountinfo['real_name'];
        $orderdata['update_at'] = time();
        DB::beginTransaction();
        try {
            OrderRecovery::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->create($orderdata);
            foreach ($sub_arr as &$sub) {
                $sub['pid'] = $info->id;
                $sub['mem_id'] = $meminfo->id;
            }
            OrderRecoveryGoods::where(['cp_id' => $cp_id, 'is_del' => 1, 'pid' => $info->id])->update(['is_del' => 2, 'del_at' => time()]);
            OrderRecoveryGoods::insert($sub_arr);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '积分增加失败' . $e->getMessage()]);
        }

        return response()->json(['code' => '000', 'msg' => '开单成功']);
    }

    /**
     * 审核通过
     */
    public function doorderauditsuccess(Request $request)
    {
        $id = $request->id ?? 0;
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $info = OrderRecovery::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
//        if ($info->audit_status != 1) {
//            return response()->json(['code' => '001', 'msg' => '该订单已审核']);
//        }
        // if($info->is_maker!=1){
        //     return response()->json(['code' => '001', 'msg' => '该订单挂单中不可审核']);
        // }

        $meminfo = Member::where(['cp_id' => $cp_id, 'id' => $info->mem_id, 'is_del' => 1])->first();

        DB::beginTransaction();
        try {
            OrderRecovery::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['audit_status' => 2, 'audit_at' => time()]);
            OrderCommissionLog::where(['pid' => $id, 'cp_id' => $cp_id])->update(['audit_status' => 2, 'audit_at' => time()]);
            OrderRecoveryGoods::where(['pid' => $id, 'is_del' => 1])->update(['audit_status' => 2, 'audit_at' => time()]);

            $recoverygoodslist = OrderRecoveryGoods::where(['pid' => $id, 'is_del' => 1])->get()->toArray();

            foreach ($recoverygoodslist as $recoverygoods) {
                //回收操作
                if ($recoverygoods['change_type'] == 1) {
                    //添加到旧料
                    $infobygoods_sn_code = GoodsStockList::where(['cp_id' => $cp_id, 'goods_sn_code' => $recoverygoods['goods_sn_code']])->first();
                    if ($infobygoods_sn_code) {
                        $oldmaterialstockdata = $infobygoods_sn_code;
                        $oldmaterialstockdata['cp_id'] = $cp_id;
                        $oldmaterialstockdata['store_id'] = $info->store_id;
                        $oldmaterialstockdata['count'] = $recoverygoods['count'];

                        unset($oldmaterialstockdata['id']);
                    } else {
                        $oldmaterialstockdata = [];
                        $oldmaterialstockdata['cp_id'] = $cp_id;
                        $oldmaterialstockdata['store_id'] = $info->store_id;
                        $oldmaterialstockdata['count'] = $recoverygoods['count'];
                        $oldmaterialstockdata['goods_sn_code'] = $recoverygoods['goods_sn_code'];
                        $oldmaterialstockdata['goods_category_id'] = $recoverygoods['goods_category_id'];
                    }
                    $oldmaterialstockdata['order_sncode'] = $info->order_sn;
                    $oldmaterialstockdata['stockin_at'] = time();
                    $oldmaterialstockdata['create_at'] = time();
                    $oldmaterialstockdata['type'] = 2;
                    $oldmaterialstockdata['stock_type'] = $recoverygoods['recovery_type'];
                    $oldmaterialstockdata['piece_weight'] = $recoverygoods['weight'] * $recoverygoods['count'];
                    $oldmaterialstockdata['piece_weight_new'] = ($recoverygoods['weight'] - $recoverygoods['loss_weight']) * $recoverygoods['count'];
                    $oldmaterialstockdata['back_company_price'] = $recoverygoods['old_recovery_price'];
                    $oldmaterialstockdata['label_price'] = $recoverygoods['d_price'];
                    $oldmaterialstockdata['exchange_amount'] = $recoverygoods['money'];
                    $oldmaterialstockdata['remark'] = $recoverygoods['remark'];
                    $oldmaterialstockdata['create_account_id'] = $accountinfo['id'];
                    $oldmaterialstockdata['update_account_id'] = $accountinfo['id'];
                    $oldmaterialstockdata['create_account_real_name'] = $accountinfo['real_name'];
                    $oldmaterialstockdata['update_account_real_name'] = $accountinfo['real_name'];
                    $oldmaterialstockdata['dold_fee'] = $recoverygoods['dold_fee'];
                    $oldmaterialstockdata['valuations'] = $recoverygoods['valuations'];
                    $oldmaterialstockdata['total_cost_fee'] = $recoverygoods['total_cost_fee'] ?? 0;

                    if (!is_array($oldmaterialstockdata)) {
                        $oldmaterialstockdata = json_decode($oldmaterialstockdata, true);
                    }
                    Stock::create($oldmaterialstockdata);
                    //旧料日志
                    $oldLog = [];
                    $oldLog['cp_id'] = $oldmaterialstockdata['cp_id'];
                    $oldLog['store_id'] = $oldmaterialstockdata['store_id'];
                    $oldLog['start_store_id'] = $oldmaterialstockdata['store_id'];
                    $oldLog['target_store_id'] = $oldmaterialstockdata['store_id'];
                    $oldLog['order_sncode'] = $oldmaterialstockdata['order_sncode'];
                    $oldLog['goods_category_id'] = $oldmaterialstockdata['goods_category_id'];
                    $oldLog['stock_type'] = $oldmaterialstockdata['stock_type'];
                    $oldLog['piece_weight'] = $oldmaterialstockdata['piece_weight'];
                    $oldLog['count'] = $oldmaterialstockdata['count'];
                    $oldLog['cf_no'] = $oldmaterialstockdata['cf_no'] ?? '';
                    $oldLog['create_account_id'] = $oldmaterialstockdata['create_account_id'];
                    $oldLog['create_account_real_name'] = $oldmaterialstockdata['create_account_real_name'];
                    $oldLog['create_at'] = $oldmaterialstockdata['create_at'];

                    (new \App\Store\Models\OldMaterial\Log())->addLog($oldLog, 8);
                } else {
                    //上柜操作
                    $infoGoods = GoodsStockList::query()->where(['cp_id' => $cp_id, 'store_id' => $info->store_id, 'goods_sn_code' => $recoverygoods['goods_sn_code'], 'is_del' => 1])->first();
                    if (empty($infoGoods)) {
                        return response()->json(['code' => '001', 'msg' => '该条码' . $recoverygoods['goods_sn_code'] . '不存在，不能上柜']);
                    }
                    $infoGoods = $infoGoods->toArray();
                    $is_gram = GoodsCategory::query()
                        ->where(['cp_id' => $cp_id, 'store_id' => $info->store_id])
                        ->where('id', $infoGoods['goods_category_id'])
                        ->value('is_gram') ?? 0;

                    $count = ($infoGoods['count'] ?? 0) + $recoverygoods['count'];
                    $weight = $recoverygoods['weight'] - $recoverygoods['loss_weight'];

                    // 此处需要根据商品去计算
                    if ($infoGoods['is_code_more'] == 2) {
                        $recoverygoods['total_netglod_weight'] = $recoverygoods['weight'];
                    } else {
                        $recoverygoods['total_netglod_weight'] = $infoGoods['netglod_weight'] * $recoverygoods['count'];
                    }
                    list($total_cost_fee, $costglod_price, $piececost_fee) = (new Goods())->incrTotalCost($infoGoods, $recoverygoods, $is_gram);

                    // 如果是一码多货
                    $stockData = [];
                    $stockData['count'] = $count;
                    $stockData['total_cost_fee'] = $total_cost_fee;
                    $stockData['costglod_price'] = $costglod_price;
                    $stockData['piececost_fee'] = $piececost_fee;

                    if ((int)$infoGoods['is_code_more'] == 2) {
                        $stockData['total_netglod_weight'] = $infoGoods['total_netglod_weight'] + $weight;
                        $infoGoods['total_netglod_weight'] = $weight;
                    } else {
                        $stockData['piece_weight'] = $infoGoods['piece_weight'] > 0 ? $infoGoods['piece_weight'] : 0;
                        $stockData['netglod_weight'] = $infoGoods['netglod_weight'] > 0 ? $infoGoods['netglod_weight'] : 0;
                        $stockData['total_piece_weight'] = $stockData['piece_weight'] * $count;
                        $stockData['total_netglod_weight'] = $stockData['netglod_weight'] * $count;
                        // 日志数据
                        $infoGoods['count'] = $recoverygoods['count'];
                        $infoGoods['piece_weight'] = $stockData['piece_weight'];
                        $infoGoods['netglod_weight'] = $stockData['netglod_weight'];
                        $infoGoods['total_piece_weight'] = $stockData['piece_weight'] * $recoverygoods['count'];
                        $infoGoods['total_netglod_weight'] = $stockData['netglod_weight'] * $recoverygoods['count'];
                    }

                    GoodsStockList::query()
                        ->where(['cp_id' => $cp_id, 'store_id' => $info->store_id, 'goods_sn_code' => $recoverygoods['goods_sn_code']])
                        ->update($stockData);
                    //此处需要取回收的总成本
                    $infoGoods['total_cost_fee'] = $recoverygoods['total_cost_fee'];
                    $infoGoods['costglod_price'] = $stockData['costglod_price'];
                    $infoGoods['piececost_fee'] = $stockData['piececost_fee'];
                    Goods::goodsLog($request, 0, $info->store_id, $infoGoods, intval($recoverygoods['count']), 93, '');
                }
            }

            $info->mem_id > 0 && Member::where(['id' => $info->mem_id, 'cp_id' => $cp_id, 'is_del' => 1])->update([
                'shopping_times' => DB::raw('shopping_times + 1 '),
                'shopping_money_total' => DB::raw('shopping_money_total + ' . $info->total_money),
                'avg_shopping_money' => intval(($meminfo->shopping_money_total + $info->total_money) / ($meminfo->shopping_times + 1)),
                'max_shopping_money' => ($info->total_money > $meminfo->max_shopping_money ? $info->total_money : $meminfo->max_shopping_money),
                'min_shopping_money' => ($info->total_money < $meminfo->min_shopping_money ? $info->total_money : $meminfo->min_shopping_money),
                'last_shopping_at' => $info->create_at
            ]);

            //计算绩效？
            //订单成功发送短信
            $info->count = array_sum(array_column($recoverygoodslist, 'count'));
            $info->money = array_sum(array_column($recoverygoodslist, 'money'));
            Financial::createMoneyLogByPaymoney($cp_id, $info->store_id, $info->pay_type_id, $info->total_money, $info->order_sn, -2, $info->mixed_payment, '销售费用');
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '审核失败' . $e->getLine() . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '订单审核成功']);
    }


    public function doorderauditsuccessmore(Request $request)
    {
        $ids = $request->ids;
        $ids = is_array($ids) ? $ids : (is_array(json_decode($ids, true)) ? json_decode($ids, true) : []);


        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];


        $info_more_arr = OrderRecovery::where(['cp_id' => $cp_id, 'audit_status' => 1])->whereIn('id', $ids)->get();

        if (count($info_more_arr) != count($ids)) {
            return response()->json(['code' => '001', 'msg' => '存在已审核订单']);
        }


        DB::beginTransaction();
        try {
            foreach ($info_more_arr as $info) {
                $id = $info->id;
                $meminfo = Member::where(['cp_id' => $cp_id, 'id' => $info->mem_id, 'is_del' => 1])->first();

                OrderRecovery::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['audit_status' => 2, 'audit_at' => time()]);
                OrderCommissionLog::where(['pid' => $id, 'cp_id' => $cp_id])->update(['audit_status' => 2, 'audit_at' => time()]);
                OrderRecoveryGoods::where(['pid' => $id, 'is_del' => 1])->update(['audit_status' => 2, 'audit_at' => time()]);
                //上柜操作

                //回收操作
                $recoverygoodslist = OrderRecoveryGoods::where(['pid' => $id, 'is_del' => 1])->get()->toArray();
                foreach ($recoverygoodslist as $recoverygoods) {

                    if ($recoverygoods['change_type'] == 1) {
                        //添加到旧料
                        $infobygoods_sn_code = GoodsStockList::where(['cp_id' => $cp_id, 'goods_sn_code' => $recoverygoods['goods_sn_code']])->first();
                        if ($infobygoods_sn_code) {
                            $oldmaterialstockdata = $infobygoods_sn_code;
                            $oldmaterialstockdata['cp_id'] = $cp_id;
                            $oldmaterialstockdata['store_id'] = $info->store_id;
                            $oldmaterialstockdata['count'] = $recoverygoods['count'];

                            unset($oldmaterialstockdata['id']);
                        } else {
                            $oldmaterialstockdata = [];
                            $oldmaterialstockdata['cp_id'] = $cp_id;
                            $oldmaterialstockdata['store_id'] = $info->store_id;
                            $oldmaterialstockdata['count'] = $recoverygoods['count'];
                            $oldmaterialstockdata['goods_sn_code'] = $recoverygoods['goods_sn_code'];
                            $oldmaterialstockdata['goods_category_id'] = $recoverygoods['goods_category_id'];
                        }
                        $oldmaterialstockdata['order_sncode'] = $info->order_sn;
                        $oldmaterialstockdata['stockin_at'] = time();
                        $oldmaterialstockdata['create_at'] = time();
                        $oldmaterialstockdata['type'] = 2;
                        $oldmaterialstockdata['stock_type'] = $recoverygoods['recovery_type'];
                        $oldmaterialstockdata['piece_weight'] = $recoverygoods['weight'] * $recoverygoods['count'];
                        $oldmaterialstockdata['piece_weight_new'] = ($recoverygoods['weight'] - $recoverygoods['loss_weight']) * $recoverygoods['count'];
                        $oldmaterialstockdata['back_company_price'] = $recoverygoods['old_recovery_price'];
                        $oldmaterialstockdata['label_price'] = $recoverygoods['d_price'];
                        $oldmaterialstockdata['exchange_amount'] = $recoverygoods['money'];
                        $oldmaterialstockdata['remark'] = $recoverygoods['remark'];
                        $oldmaterialstockdata['create_account_id'] = $accountinfo['id'];
                        $oldmaterialstockdata['update_account_id'] = $accountinfo['id'];
                        $oldmaterialstockdata['create_account_real_name'] = $accountinfo['real_name'];
                        $oldmaterialstockdata['update_account_real_name'] = $accountinfo['real_name'];
                        $oldmaterialstockdata['dold_fee'] = $recoverygoods['dold_fee'];
                        $oldmaterialstockdata['valuations'] = $recoverygoods['valuations'];
                        $oldmaterialstockdata['total_cost_fee'] = $recoverygoods['total_cost_fee'] ?? 0;
                        if (!is_array($oldmaterialstockdata)) {
                            $oldmaterialstockdata = json_decode($oldmaterialstockdata, true);
                        }
                        Stock::create($oldmaterialstockdata);
                        //旧料日志
                        $oldLog = [];
                        $oldLog['cp_id'] = $oldmaterialstockdata['cp_id'];
                        $oldLog['store_id'] = $oldmaterialstockdata['store_id'];
                        $oldLog['start_store_id'] = $oldmaterialstockdata['store_id'];
                        $oldLog['target_store_id'] = $oldmaterialstockdata['store_id'];
                        $oldLog['order_sncode'] = $oldmaterialstockdata['order_sncode'];
                        $oldLog['goods_category_id'] = $oldmaterialstockdata['goods_category_id'];
                        $oldLog['stock_type'] = $oldmaterialstockdata['stock_type'];
                        $oldLog['piece_weight'] = $oldmaterialstockdata['piece_weight'];
                        $oldLog['count'] = $oldmaterialstockdata['count'];
                        $oldLog['cf_no'] = $oldmaterialstockdata['cf_no'] ?? '';
                        $oldLog['create_account_id'] = $oldmaterialstockdata['create_account_id'];
                        $oldLog['create_account_real_name'] = $oldmaterialstockdata['create_account_real_name'];
                        $oldLog['create_at'] = $oldmaterialstockdata['create_at'];

                        (new \App\Store\Models\OldMaterial\Log())->addLog($oldLog, 8);
                    } else {

                        //上柜操作
                        $infoGoods = GoodsStockList::query()->where(['cp_id' => $cp_id, 'store_id' => $info->store_id, 'goods_sn_code' => $recoverygoods['goods_sn_code'], 'is_del' => 1])->first();
                        if (empty($infoGoods)) {
                            return response()->json(['code' => '001', 'msg' => '该条码' . $recoverygoods['goods_sn_code'] . '不存在，不能上柜']);
                        }
                        $infoGoods = $infoGoods->toArray();
                        $is_gram = GoodsCategory::query()
                            ->where(['cp_id' => $cp_id, 'store_id' => $info->store_id])
                            ->where('id', $infoGoods['goods_category_id'])
                            ->value('is_gram') ?? 0;

                        $count = ($infoGoods['count'] ?? 0) + $recoverygoods['count'];
                        $weight = $recoverygoods['weight'] - $recoverygoods['loss_weight'];

                        // 此处需要根据商品去计算
                        if ($infoGoods['is_code_more'] == 2) {
                            $recoverygoods['total_netglod_weight'] = $recoverygoods['weight'];
                        } else {
                            $recoverygoods['total_netglod_weight'] = $infoGoods['netglod_weight'] * $recoverygoods['weight'];
                        }
                        list($total_cost_fee, $costglod_price, $piececost_fee) = (new Goods())->incrTotalCost($infoGoods, $recoverygoods, $is_gram);

                        // 如果是一码多货
                        $stockData = [];
                        $stockData['count'] = $count;
                        $stockData['total_cost_fee'] = $total_cost_fee;
                        $stockData['costglod_price'] = $costglod_price;
                        $stockData['piececost_fee'] = $piececost_fee;

                        if ((int)$infoGoods['is_code_more'] == 2) {
                            $stockData['total_netglod_weight'] = $infoGoods['total_netglod_weight'] + $weight;
                            $infoGoods['total_netglod_weight'] = $weight;
                        } else {
                            $stockData['piece_weight'] = $infoGoods['piece_weight'] > 0 ? $infoGoods['piece_weight'] : $weight;
                            $stockData['netglod_weight'] = $infoGoods['netglod_weight'] > 0 ? $infoGoods['netglod_weight'] : $weight;
                            $stockData['total_piece_weight'] = $stockData['piece_weight'] * $count;
                            $stockData['total_netglod_weight'] = $stockData['netglod_weight'] * $count;
                            // 日志数据
                            $infoGoods['count'] = $recoverygoods['count'];
                            $infoGoods['piece_weight'] = $stockData['piece_weight'];
                            $infoGoods['netglod_weight'] = $stockData['netglod_weight'];
                            $infoGoods['total_piece_weight'] = $stockData['piece_weight'] * $recoverygoods['count'];
                            $infoGoods['total_netglod_weight'] = $stockData['netglod_weight'] * $recoverygoods['count'];
                        }

                        GoodsStockList::query()
                            ->where(['cp_id' => $cp_id, 'store_id' => $info->store_id, 'goods_sn_code' => $recoverygoods['goods_sn_code']])
                            ->update($stockData);

                        // 此处需要覆盖总成本
                        $infoGoods['total_cost_fee'] = $recoverygoods['total_cost_fee'];
                        $infoGoods['costglod_price'] = $stockData['costglod_price'];
                        $infoGoods['piececost_fee'] = $stockData['piececost_fee'];
                        Goods::goodsLog($request, 0, intval($infoGoods['store_id']), $infoGoods, intval($recoverygoods['count']), 93, $info->order_sn);

                    }
                }

                $info->mem_id > 0 && Member::where(['id' => $info->mem_id, 'cp_id' => $cp_id, 'is_del' => 1])->update([
                    'shopping_times' => DB::raw('shopping_times + 1 '),
                    'shopping_money_total' => DB::raw('shopping_money_total + ' . $info->total_money),
                    'avg_shopping_money' => intval(($meminfo->shopping_money_total + $info->total_money) / ($meminfo->shopping_times + 1)),
                    'max_shopping_money' => ($info->total_money > $meminfo->max_shopping_money ? $info->total_money : $meminfo->max_shopping_money),
                    'min_shopping_money' => ($info->total_money < $meminfo->min_shopping_money ? $info->total_money : $meminfo->min_shopping_money),
                    'last_shopping_at' => $info->create_at
                ]);

                //计算绩效？
                //订单成功发送短信
                $info->count = array_sum(array_column($recoverygoodslist, 'count'));
                $info->money = array_sum(array_column($recoverygoodslist, 'money'));
                Financial::createMoneyLogByPaymoney($cp_id, $info->store_id, $info->pay_type_id, $info->total_money, $info->order_sn, -2, $info->mixed_payment, '销售费用');

            }


            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '审核失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '订单审核成功']);

    }

    /**
     * 审核取消
     */
    public function doorderauditcancel(Request $request)
    {
        $id = $request->id ?? 0;
        $audit_remark = $request->audit_remark ?? '';
        if ($audit_remark == '') {
            return response()->json(['code' => '001', 'msg' => '请输入撤单原因']);
        }
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];

        $info = OrderRecovery::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->first();
        if (empty($info)) {
            return response()->json(['code' => '001', 'msg' => '订单不存在']);
        }

        if (($accountinfo['type'] == 1 || $accountinfo['type'] == 2) && date('Y-m-d', $info->create_at) != date('Y-m-d') && $info->audit_status == 2) {

            return response()->json(['code' => '001', 'msg' => '店长只可撤单当日订单']);
        }


        if ($info->audit_status > 2) {
            return response()->json(['code' => '001', 'msg' => '该订单已撤单']);
        }

        $meminfo = Member::where(['cp_id' => $cp_id, 'id' => $info->mem_id, 'is_del' => 1])->first();

        //旧料表
        $oldmaterialcount = Stock::where(['order_sncode' => $info->order_sn, 'cp_id' => $cp_id])->get()->toArray();
        if (!empty($oldmaterialcount)) {
            foreach ($oldmaterialcount as $v) {
                if ($v['is_del'] == 2 || $v['stock_status'] != 1) {
                    return response()->json(['code' => '001', 'msg' => '该订单下的旧料不在库，不支持撤单']);
                }
            }
        }


        //旧料库存表
        $recoverygoodslist = OrderRecoveryGoods::where(['pid' => $id, 'is_del' => 1])->get()->toArray();

        foreach ($recoverygoodslist as $recoverygoods) {
            if ($recoverygoods['change_type'] != 1) {
                //上柜
                $goodinfo = GoodsStockList::where(['cp_id' => $cp_id, 'store_id' => $info->store_id, 'goods_sn_code' => $recoverygoods['goods_sn_code']])
                    ->select(['total_netglod_weight', 'total_piece_weight', 'is_del'])
                    ->first()
                    ->toArray();
                if ($goodinfo['is_del'] != 1) {
                    return response()->json(['code' => '001', 'msg' => '该订单商品库存不足不支持撤单']);
                }
                $recoverygoodsweight = $recoverygoods['weight'] * $recoverygoods['count'];
                if ($recoverygoods['recovery_type'] == 1) {
                    //total_netglod_weight
                    if ($recoverygoodsweight > $goodinfo['total_netglod_weight']) {
                        return response()->json(['code' => '001', 'msg' => '该订单商品库存不足不支持撤单']);
                    }
                } else {
                    //total_piece_weight
                    if ($recoverygoodsweight > $goodinfo['total_piece_weight']) {
                        return response()->json(['code' => '001', 'msg' => '该订单商品库存不足不支持撤单']);
                    }
                }
            }

        }
        $order_sns = array_column($recoverygoodslist, 'order_sncode');

        DB::beginTransaction();
        try {
            OrderRecovery::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['audit_status' => 3, 'audit_at' => time(), 'audit_remark' => $audit_remark]);
            OrderCommissionLog::where(['pid' => $id, 'cp_id' => $cp_id])->update(['audit_status' => 3, 'audit_at' => time()]);
            OrderRecoveryGoods::where(['pid' => $id, 'is_del' => 1])->update(['audit_status' => 3, 'audit_at' => time()]);
            //回收操作
            //旧料库
            Stock::where([
                ['order_sncode', '=', $info->order_sn],
                ['stock_status', '=', 1],
            ])
                ->update([
                    'count' => 0,
                    'piece_weight' => 0,
                    'piece_weight_new' => 0,
                    'exchange_amount' => 0,
                    'stock_status' => 7, //旧料库存 撤单
                ]);

            //回收旧料处理-上柜取消
            foreach ($recoverygoodslist as $recoverygoods) {
                if ($recoverygoods['change_type'] != 1) {
                    //上柜
                    $goodsStock = GoodsStockList::where(['cp_id' => $cp_id, 'store_id' => $info->store_id, 'goods_sn_code' => $recoverygoods['goods_sn_code'], 'is_del' => 1])->first();
                    if ($goodsStock) {
                        $goodsStock = $goodsStock->toArray();

                        $is_gram = GoodsCategory::query()
                            ->where(['cp_id' => $cp_id, 'store_id' => $info->store_id])
                            ->where('id', $goodsStock['goods_category_id'])
                            ->value('is_gram') ?? 0;

                        $weight = $recoverygoods['weight'] - $recoverygoods['loss_weight'];
                        //recovery_type =1按克，2标价
                        $count = $goodsStock['count'] - $recoverygoods['count'];
                        $weight = $recoverygoods['weight'] - $recoverygoods['loss_weight'];
                        if ($recoverygoods['recovery_type'] == 1) {
                            if ($goodsStock['is_code_more'] == 2) {
                                $log_total_netglod_weight = $weight;
                                $log_total_piece_weight = 0;

                                $total_piece_weight = 0;
                                $total_netglod_weight = $goodsStock['total_netglod_weight'] - $weight;

                                $recoverygoods['total_netglod_weight'] = $log_total_netglod_weight;
                            } else {
                                // 非一码多货
                                $total_netglod_weight = $goodsStock['netglod_weight'] * $count;
                                $total_piece_weight = $goodsStock['piece_weight'] * $count;

                                $log_total_netglod_weight = $goodsStock['netglod_weight'] * $recoverygoods['count'];
                                $log_total_piece_weight = $goodsStock['piece_weight'] * $recoverygoods['count'];

                                $recoverygoods['total_netglod_weight'] = $log_total_netglod_weight;
                            }
                        } else {
                            $total_piece_weight = $goodsStock['piece_weight'] * $count;
                            $total_netglod_weight = $goodsStock['netglod_weight'] * $count;

                            $log_total_piece_weight = $goodsStock['piece_weight'] * $recoverygoods['count'];
                            $log_total_netglod_weight = $goodsStock['netglod_weight'] * $recoverygoods['count'];

                            $recoverygoods['total_piece_weight'] = $log_total_piece_weight;
                            $recoverygoods['total_netglod_weight'] = $goodsStock['netglod_weight'] * $recoverygoods['count'];;
                        }

                        list($deduct_total_cost_fee, $remaining_cost_fee) = (new Goods())->deductTotalCost($goodsStock, $recoverygoods);


                        $goodsStock['count'] = $count;
                        $goodsStock['total_netglod_weight'] = $total_netglod_weight ?? 0;
                        $goodsStock['total_piece_weight'] = $total_piece_weight ?? 0;

                        //$total_cost_fee = (new Goods())->computeOriginalTotalCost($goodsStock, $is_gram);
                        $stockArr = [
                            'count' => $count,
                            'total_netglod_weight' => $goodsStock['total_netglod_weight'],
                            'total_piece_weight' => $goodsStock['total_piece_weight'],
                            'total_cost_fee' => $remaining_cost_fee
                        ];
                        GoodsStockList::query()
                            ->where(['cp_id' => $cp_id, 'store_id' => $info->store_id, 'goods_sn_code' => $recoverygoods['goods_sn_code']])
                            ->update($stockArr);
                        $stockdata = $goodsStock;
                        $stockdata['count'] = $recoverygoods['count'];
                        $stockdata['total_netglod_weight'] = $log_total_netglod_weight ?? 0;
                        $stockdata['total_piece_weight'] = $log_total_piece_weight ?? 0;
                        Goods::goodsLog($request, 0, intval($stockdata['store_id']), $stockdata, intval($stockdata['count']), 94, $info->order_sn);
                    }
                }

            }

            if (empty($meminfo->shopping_times) || intval($meminfo->shopping_times) <= 1) {
                $avg_shopping_money = 0;
            } else {
                $avg_shopping_money = intval(($meminfo->shopping_money_total - $info->total_money) / ($meminfo->shopping_times - 1));
            }
            //余额变动
            if ($info->mem_id > 0) {
                $memData['shopping_times'] = $info->shopping_times > 0 ? ($info->shopping_times - 1) : 0;
                $memData['shopping_money_total'] = $info->shopping_money_total > 0 ? ($info->shopping_money_total - $info->total_money) : 0;
                $memData['avg_shopping_money'] = $avg_shopping_money;
                $memData['last_shopping_at'] = $info->create_at;
                Member::query()->where(['id' => $info->mem_id, 'cp_id' => $cp_id, 'is_del' => 1])
                    ->update($memData);
            }


            // Financial::createMoneyLogByPaymoneyAuditCancel($cp_id, $info->store_id, $info->pay_type_id, $info->total_money, $info->order_sn, -2, '纯回收撤单费用');
            Financial::createMoneyLogByPaymoney($cp_id, $info->store_id, $info->pay_type_id, $info->total_money, $info->order_sn, -2, $info->mixed_payment, '纯回收撤单费用');


            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '审核失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '订单撤销成功']);
    }

    public function doorderauditcancelmore(Request $request)
    {
        $ids = $request->ids;
        $ids = is_array($ids) ? $ids : (is_array(json_decode($ids, true)) ? json_decode($ids, true) : []);
        $audit_remark = $request->audit_remark ?? '';
        if ($audit_remark == '') {
            return response()->json(['code' => '001', 'msg' => '请输入撤单原因']);
        }
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];

        $info_more_arr = OrderRecovery::query()
            ->where([
                ['cp_id', '=', $cp_id],
                ['audit_status', '<', 3]
            ])->whereIn('id', $ids)->get();

        if (count($info_more_arr) != count($ids)) {
            return response()->json(['code' => '001', 'msg' => '存在已审核订单']);
        }
        $recoverys = $info_more_arr->toArray();
        if ($accountinfo['type'] == 1 || $accountinfo['type'] == 2) {
            foreach ($recoverys as $info2) {
                if (date('Y-m-d', $info2['create_at']) != date('Y-m-d')) {
                    return response()->json(['code' => '001', 'msg' => '店长只可撤单当日订单']);
                }
            }


        }

        //旧料库存表
        $recoverygoodslist = OrderRecoveryGoods::whereIn('pid', $ids)->where('is_del', 1)->get()->toArray();

        $order_sns = array_column($recoverys, 'order_sn');
        //旧料表
        $oldmaterialcount = Stock::query()
            ->where(['cp_id' => $cp_id])
            ->whereIn('order_sncode', $order_sns)
            ->get()
            ->toArray();
        if (!empty($oldmaterialcount)) {
            foreach ($oldmaterialcount as $v) {
                if ($v['is_del'] == 2 || $v['stock_status'] != 1) {
                    return response()->json(['code' => '001', 'msg' => '该订单下的旧料不在库，不支持撤单']);
                }
            }
        }

        foreach ($recoverygoodslist as $recoverygoods) {
            if ($recoverygoods['change_type'] != 1) {
                //上柜
                $goodinfo = GoodsStockList::where(['cp_id' => $cp_id, 'store_id' => $recoverygoods->store_id, 'goods_sn_code' => $recoverygoods['goods_sn_code']])
                    ->select(['total_netglod_weight', 'total_piece_weight', 'is_del'])
                    ->first()
                    ->toArray();
                if ($goodinfo['is_del'] != 1) {
                    return response()->json(['code' => '001', 'msg' => '该订单商品库存不足不支持撤单']);
                }
                $recoverygoodsweight = $recoverygoods['weight'] * $recoverygoods['count'];
                if ($recoverygoods['recovery_type'] == 1) {
                    //total_netglod_weight
                    if ($recoverygoodsweight > $goodinfo['total_netglod_weight']) {
                        return response()->json(['code' => '001', 'msg' => '该订单商品库存不足不支持撤单']);
                    }
                } else {
                    //total_piece_weight
                    if ($recoverygoodsweight > $goodinfo['total_piece_weight']) {
                        return response()->json(['code' => '001', 'msg' => '该订单商品库存不足不支持撤单']);
                    }
                }
            }

        }

        DB::beginTransaction();
        try {
            foreach ($info_more_arr as $info) {
                //旧料库
                Stock::where([
                    ['order_sncode', '=', $info->order_sn],
                    ['stock_status', '=', 1],
                ])
                    ->update([
                        'count' => 0,
                        'piece_weight' => 0,
                        'piece_weight_new' => 0,
                        'exchange_amount' => 0,
                        'stock_status' => 7, //旧料库存 撤单
                    ]);

                //回收旧料处理-上柜
                foreach ($recoverygoodslist as $recoverygoods) {
                    if ($recoverygoods['change_type'] != 1) {
                        //上柜
                        $goodsStock = GoodsStockList::where(['cp_id' => $cp_id, 'store_id' => $info->store_id, 'goods_sn_code' => $recoverygoods['goods_sn_code'], 'is_del' => 1])->first();
                        if ($goodsStock) {
                            $goodsStock = $goodsStock->toArray();
                            //recovery_type =1按克，2标价
                            $count = $goodsStock['count'] - $recoverygoods['count'];
                            $weight = $recoverygoods['weight'] - $recoverygoods['loss_weight'];
                            if ($recoverygoods['recovery_type'] == 1) {
                                if ($goodsStock['is_code_more'] == 2) {
                                    $log_total_netglod_weight = $weight;
                                    $log_total_piece_weight = 0;

                                    $recoverygoods['total_netglod_weight'] = $log_total_netglod_weight;

                                    $total_piece_weight = 0;
                                    $total_netglod_weight = $goodsStock['total_netglod_weight'] - $weight;
                                } else {
                                    // 非一码多货
                                    $total_piece_weight = $goodsStock['piece_weight'] * $count;
                                    $total_netglod_weight = $goodsStock['netglod_weight'] * $count;

                                    $log_total_netglod_weight = $goodsStock['netglod_weight'] * $recoverygoods['count'];
                                    $log_total_piece_weight = $goodsStock['piece_weight'] * $recoverygoods['count'];

                                    $recoverygoods['total_netglod_weight'] = $log_total_netglod_weight;
                                }
                            } else {
                                $total_piece_weight = $goodsStock['piece_weight'] * $count;
                                $total_netglod_weight = $goodsStock['netglod_weight'] * $count;

                                $log_total_netglod_weight = $goodsStock['netglod_weight'] * $recoverygoods['count'];
                                $log_total_piece_weight = $goodsStock['piece_weight'] * $recoverygoods['count'];
                                $recoverygoods['total_netglod_weight'] = $goodsStock['netglod_weight'] * $recoverygoods['count'];;
                            }

                            $is_gram = GoodsCategory::query()
                                ->where(['cp_id' => $cp_id, 'store_id' => $info->store_id])
                                ->where('id', $goodsStock['goods_category_id'])
                                ->value('is_gram') ?? 0;

                            $goodsStock['count'] = $count;
                            $goodsStock['total_netglod_weight'] = $total_netglod_weight ?? 0;
                            $goodsStock['total_piece_weight'] = $total_piece_weight ?? 0;
                            list($deduct_total_cost_fee, $remaining_cost_fee) = (new Goods())->deductTotalCost($goodsStock, $recoverygoods);

                            // $total_cost_fee = (new Goods())->computeOriginalTotalCost($goodsStock, $is_gram);
                            $stockArr = [
                                'count' => $count,
                                'total_netglod_weight' => $goodsStock['total_netglod_weight'],
                                'total_piece_weight' => $goodsStock['total_piece_weight'],
                                'total_cost_fee' => $remaining_cost_fee
                            ];
                            GoodsStockList::query()
                                ->where(['cp_id' => $cp_id, 'store_id' => $info->store_id, 'goods_sn_code' => $recoverygoods['goods_sn_code']])
                                ->update($stockArr);
                            $stockdata = $goodsStock;
                            $stockdata['count'] = $recoverygoods['count'];
                            $stockdata['total_netglod_weight'] = $log_total_netglod_weight ?? 0;
                            $stockdata['total_piece_weight'] = $log_total_piece_weight ?? 0;
                            Goods::goodsLog($request, 0, intval($stockdata['store_id']), $stockdata, intval($stockdata['count']), 94, $info->order_sn);
                        }
                    }

                }

                //余额变动
                if ($info->mem_id > 0) {
                    Member::where(['id' => $info->mem_id, 'cp_id' => $cp_id, 'is_del' => 1])->update([
                        'shopping_times' => DB::raw('shopping_times - 1 '),
                        'shopping_money_total' => DB::raw('shopping_money_total - ' . $info->total_money),
                        'avg_shopping_money' => DB::raw('shopping_money_total / shopping_times '),
                        'last_shopping_at' => $info->create_at
                    ]);
                }

                // Financial::createMoneyLogByPaymoneyAuditCancel($cp_id, $info->store_id, $info->pay_type_id, $info->total_money, $info->order_sn, -2, $info->$mixed_payment,'纯回收撤单费用');
                Financial::createMoneyLogByPaymoney($cp_id, $info->store_id, $info->pay_type_id, $info->total_money, $info->order_sn, -2, $info->mixed_payment, '纯回收撤单费用');

            }


            OrderCommissionLog::where(['cp_id' => $cp_id])->whereIn('pid', $ids)->update(['audit_status' => 3, 'audit_at' => time()]);
            OrderRecovery::where(['cp_id' => $cp_id, 'is_del' => 1, 'audit_status' => 1])->whereIn('id', $ids)->update(['audit_status' => 3, 'audit_at' => time(), 'audit_remark' => $audit_remark]);

            OrderRecoveryGoods::where(['is_del' => 1])->whereIn('pid', $ids)->update(['audit_status' => 3, 'audit_at' => time()]);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '审核失败' . $e->getMessage()]);
        }

        return response()->json(['code' => '000', 'msg' => '订单撤销成功']);
    }

    /**
     * 导出
     */
    public function doexport(Request $request)
    {
        $request['isgetall'] = 1;
        $list = OrderRecovery::getList($request)['list'];

        $row = [
            ['table_header' => '纯回收开单'],
            [
                'store' => '所属门店',
                'mobile' => '会员电话',
                'real_name' => '会员姓名',
                'mem_card_no' => '会员卡号',
                'order_sn' => '订单号',
                'change_type' => '换货方式',
                'recovery_type' => '回收方式',
                'goods_catefory_name' => '旧料类别',
                'goods_sn_code' => '回收条码',
                'count' => '数量',
                'weight' => '回收重量',
                'price' => '回收单价',
                'd_price' => '回收标价',
                'discount' => '折扣',
                'dold_price' => '折旧单价',
                'dold_fee' => '折扣工费',
                'loss_weight' => '损耗重量',
                'money' => '回收金额',
                'remark' => '备注',
            ]];

        $exceldata = [];
        foreach ($list as $val) {
            $goodslist = $val['goodslist'] ?? [];
            if (!empty($goodslist)) {
                foreach ($goodslist as $item) {
                    $exceldata[] = [
                        'store' => $val['storeinfo']['store_name'],
                        'mobile' => $val['memberinfo'] ? $val['memberinfo']['mobile'] : '',
                        'real_name' => $val['memberinfo'] ? $val['memberinfo']['real_name'] : '',
                        'mem_card_no' => $val['memberinfo'] ? $val['memberinfo']['mem_card_no'] : '',
                        'order_sn' => $val['order_sn'],
                        'change_type' => (int)$item['change_type'] == 1 ? '回收' : '',
                        'recovery_type' => (int)$item['recovery_type'] == 1 ? '按克' : '标价',
                        'goods_catefory_name' => $item['goods_catefory_name'] ?? '',
                        'goods_sn_code' => $item['goods_sn_code'],
                        'count' => $item['count'] ?? '',
                        'weight' => $item['weight'],
                        'price' => $item['price'],
                        'd_price' => $item['d_price'],
                        'discount' => $item['discount'],
                        'dold_price' => $item['dold_price'],
                        'dold_fee' => $item['dold_fee'],
                        'loss_weight' => $item['loss_weight'] ?? '',
                        'money' => $item['money'] / 100,
                        'remark' => $item['remark'],
                    ];
                }
            }
        }

        $filename = '纯回收开单信息导出_' . time() . '.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata), $filename);
    }


    /**
     * 更改会员信息
     */
    public function changememinfo(Request $request)
    {
        $req_data = $request->only(['id', 'mobile', 'mem_card_no', 'real_name', 'lunar_bdate', 'solar_bdate']);
        $Validate = new ValidateOrderOrderSales('checkmember');
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $id = $req_data['id'];
        $info = OrderRecovery::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        $meminfo = Member::where(['cp_id' => $cp_id, 'mobile' => $req_data['mobile'], 'is_del' => 1])->first();

        if ($info->mem_id > 0) {
            $old_mem_id = $info->mem_id;
            $old_mem_info = Member::query()->where(['cp_id' => $cp_id, 'id' => $old_mem_id, 'is_del' => 1])->first();
            $old_mem_info = empty($old_mem_info) ? [] : $old_mem_info->toArray();
            DB::beginTransaction();
            try {
                if ($meminfo) {
                    $data = [];
                    $data['mobile'] = isset($req_data['mobile']) ? $req_data['mobile'] : '';
                    $data['mem_card_no'] = isset($req_data['mem_card_no']) ? $req_data['mem_card_no'] : '';
                    $data['real_name'] = isset($req_data['real_name']) ? $req_data['real_name'] : '';
                    $data['lunar_bdate'] = isset($req_data['lunar_bdate']) ? $req_data['lunar_bdate'] : '';
                    $data['solar_bdate'] = isset($req_data['solar_bdate']) ? $req_data['solar_bdate'] : '';
                    Member::where(['cp_id' => $cp_id, 'id' => $meminfo->id, 'is_del' => 1])->update($data);

                    OrderRecovery::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['mem_id' => $meminfo->id]);
                    OrderRecoveryGoods::where(['pid' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['mem_id' => $meminfo->id]);
                    $ins_mem_id = $meminfo->id;
                } else {
                    $data = [
                        'create_at' => time(),
                        'update_at' => time(),
                        'create_account_id' => $accountinfo['id'],
                        'update_account_id' => $accountinfo['id'],
                        'create_account_real_name' => $accountinfo['real_name'],
                        'update_account_real_name' => $accountinfo['real_name'],
                    ];
                    $data['cp_id'] = $cp_id;
                    $data['store_id'] = $info->store_id;

                    $data['mobile'] = isset($req_data['mobile']) ? $req_data['mobile'] : '';
                    $data['mem_card_no'] = isset($req_data['mem_card_no']) ? $req_data['mem_card_no'] : '';
                    $data['real_name'] = isset($req_data['real_name']) ? $req_data['real_name'] : '';
                    $data['lunar_bdate'] = isset($req_data['lunar_bdate']) ? $req_data['lunar_bdate'] : '';
                    $data['solar_bdate'] = isset($req_data['solar_bdate']) ? $req_data['solar_bdate'] : '';
                    $ins_mem_id = Member::create($data)->id;
                    CommonMember::setMemInitPoints($request, $ins_mem_id);
                    OrderRecovery::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['mem_id' => $ins_mem_id]);
                    OrderRecoveryGoods::where(['pid' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['mem_id' => $ins_mem_id]);
                }
                // 扣除更换之前的人消费次数

                if (($ins_mem_id != $old_mem_id) && !empty($old_mem_info)) {
                    if ($old_mem_info['shopping_times'] > 0) {
                        Member::where(['id' => $old_mem_id, 'cp_id' => $cp_id, 'is_del' => 1])->update([
                            'shopping_times' => DB::raw('shopping_times - 1 ')
                        ]);
                    }
                    Member::where(['id' => $ins_mem_id, 'cp_id' => $cp_id, 'is_del' => 1])->update([
                        'shopping_times' => DB::raw('shopping_times + 1 ')
                    ]);

                }

                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                return response()->json(['code' => '001', 'msg' => '会员信息绑定失败' . $e->getMessage()]);
            }

            return response()->json(['code' => '000', 'msg' => '会员信息变更成功']);
        } else {
            DB::beginTransaction();
            try {
                if ($meminfo) {
                    $ins_mem_id = $meminfo->id;
                    $data = [];
                    $data['mobile'] = isset($req_data['mobile']) ? $req_data['mobile'] : '';
                    $data['mem_card_no'] = isset($req_data['mem_card_no']) ? $req_data['mem_card_no'] : '';
                    $data['real_name'] = isset($req_data['real_name']) ? $req_data['real_name'] : '';
                    $data['lunar_bdate'] = isset($req_data['lunar_bdate']) ? $req_data['lunar_bdate'] : '';
                    $data['solar_bdate'] = isset($req_data['solar_bdate']) ? $req_data['solar_bdate'] : '';
                    Member::where(['cp_id' => $cp_id, 'id' => $meminfo->id, 'is_del' => 1])->update($data);

                    OrderRecovery::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['mem_id' => $meminfo->id]);
                    OrderRecoveryGoods::where(['pid' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['mem_id' => $meminfo->id]);
                } else {
                    $data = [
                        'create_at' => time(),
                        'update_at' => time(),
                        'create_account_id' => $accountinfo['id'],
                        'update_account_id' => $accountinfo['id'],
                        'create_account_real_name' => $accountinfo['real_name'],
                        'update_account_real_name' => $accountinfo['real_name'],
                    ];
                    $data['cp_id'] = $cp_id;
                    $data['store_id'] = $info->store_id;

                    $data['mobile'] = isset($req_data['mobile']) ? $req_data['mobile'] : '';
                    $data['mem_card_no'] = isset($req_data['mem_card_no']) ? $req_data['mem_card_no'] : '';
                    $data['real_name'] = isset($req_data['real_name']) ? $req_data['real_name'] : '';
                    $data['lunar_bdate'] = isset($req_data['lunar_bdate']) ? $req_data['lunar_bdate'] : '';
                    $data['solar_bdate'] = isset($req_data['solar_bdate']) ? $req_data['solar_bdate'] : '';
                    $ins_mem_id = Member::create($data)->id;
                    CommonMember::setMemInitPoints($request, $ins_mem_id);
                    OrderRecovery::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['mem_id' => $ins_mem_id]);
                    OrderRecoveryGoods::where(['pid' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['mem_id' => $ins_mem_id]);
                }

                if ($ins_mem_id > 0 && $info->audit_status != 1) {
                    Member::where(['id' => $ins_mem_id, 'cp_id' => $cp_id, 'is_del' => 1])->update([
                        'shopping_times' => DB::raw('shopping_times + 1 ')
                    ]);
                }

                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                return response()->json(['code' => '001', 'msg' => '会员信息绑定失败' . $e->getMessage()]);
            }
            return response()->json(['code' => '000', 'msg' => '会员信息绑定成功']);
        }


    }


    public function getorderprintdata(Request $request)
    {
        $id = $request->id ?? 0;
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        if ($id <= 0) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        $data = ServicesOrderOrderRecovery::getOrderPrintData($id, $request);
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $data]);
    }
}
